//
//  SEGParkLoginViewModel.m
//  SEGViewModel
//
//  Created by Clavis on 2020/12/9.
//

#import "SEGParkLoginViewModel.h"
#import "SEGEncryptRule.h"

@interface SEGParkLoginViewModel ()

/// 后台根据微信code查询得到的openID
@property (nonatomic, copy, readwrite) NSString *realWechatOpenID;

/// 后台返回的用户ID
@property (nonatomic, copy, readwrite) NSString *userID;

@end

@implementation SEGParkLoginViewModel

/// 使用微信登录
- (RACCommand *)wechatLoginCommand {
    if (!_wechatLoginCommand) {
        @weakify(self);
        _wechatLoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                // 数据合法性校验
                if (self.wechatCode.length <= 0) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey:kParkLoginFailMessage}];
                    [subscriber sendError:error];
                    return nil;
                }
                
                // 置空apple登录
                self.appleUserID = nil;
                
                NSDictionary *parameters = @{@"jsCode":ValueToString(self.wechatCode)};
                
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/wxCodeToLogin",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (result[@"data"] && result[@"data"][@"openId"]) {
                        self.realWechatOpenID = result[@"data"][@"openId"];
                    }
                    
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _wechatLoginCommand;
}


/// 使用apple登录
- (RACCommand *)appleLoginCommand {
    if (!_appleLoginCommand) {
        @weakify(self);
        _appleLoginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                // 数据合法性校验
                if (self.appleUserID.length == 0) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey:@"登录失败，请重试"}];
                    [subscriber sendError:error];
                    return nil;
                }
                
                // 置空wechat登录
                self.wechatCode = nil;
                self.realWechatOpenID = nil;
                
                NSDictionary *parameters = @{@"iosUserId":ValueToString(self.appleUserID)};
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/iosCodeToLogin",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _appleLoginCommand;
}


/// 微信绑定
- (RACCommand *)wechatBindComand {
    if (!_wechatBindComand) {
        @weakify(self);
        _wechatBindComand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                NSDictionary *parameters = @{@"openId":ValueToString(self.realWechatOpenID),
                                             @"tel":ValueToString(self.tel)
                };
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/wxBind",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [self handleLoginSuccess];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _wechatBindComand;
}


/// apple绑定
- (RACCommand *)appleBindComand {
    if (!_appleBindComand) {
        @weakify(self);
        _appleBindComand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
//            RACTupleUnpack(NSString *tel, NSString *appleUserID) = input;
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                NSDictionary *parameters = @{@"iosUserId":ValueToString(self.appleUserID),
                                             @"tel":ValueToString(self.tel)
                };
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/iosBind",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [self handleLoginSuccess];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _appleBindComand;
}


/// 绑定手机号（检验短信并自动登录）
- (RACCommand *)bindPhoneNumberCommand {
    if (!_bindPhoneNumberCommand) {
        @weakify(self);
        _bindPhoneNumberCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            RACTupleUnpack(NSString *tel, NSString *smsCode) = input;
//            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
                NSDictionary *parameters = @{@"smsCode":ValueToString(smsCode),
                                             @"businessCode":@"register",
                                             @"tel":ValueToString(tel)
                };
                
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/validSms",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [self handleLoginSuccess];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                
                return nil;
            }];
        }];
    }
    return _bindPhoneNumberCommand;
}


/// 通过极光token获取用户手机号(也可自动登录)
- (RACCommand *)getTelByJPUSHTokenCommand {
    if (!_getTelByJPUSHTokenCommand) {
        @weakify(self);
        _getTelByJPUSHTokenCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            /*
             operarionType
             0: 手机号自动登录
             1: 微信账号登录
             2: 苹果账号登录
             */
            RACTupleUnpack(NSString *jsToken, NSNumber *operarionType) = input;
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                if (jsToken.length == 0) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey:@"加载失败，请重试"}];
                    [subscriber sendError:error];
                    return nil;
                }
                
                NSDictionary *parameters = @{@"jgToken":ValueToString(jsToken)};
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/getTelByJgToken",nil];
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:parameters finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    
                    // 先保存手机号
                    if (result[@"data"] && [result[@"data"] isKindOfClass:[NSDictionary class]]) {
                        self.tel = ValueToString(result[@"data"][@"tel"]);
                    }
                    
                    // 1.自动登录逻辑
                    if (operarionType.integerValue == 0) {
                        if (!isSuccessed) {
                            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:kParkLoginFailMessage}];
                            [subscriber sendError:error];
                            return;
                        }
                        
                        // 取号成功 继续自动登录
                        NSString *phoneLoginUrlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/loginByTel",nil];
                        NSString *encryptTel = [SEGEncryptRule encryptByRsaWithString:self.tel];
                        NSDictionary *params = @{@"tel":encryptTel};
                        [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:phoneLoginUrlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                            if (!isSuccessed) {
                                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                                [subscriber sendError:error];
                                return;
                            }
                            self.userID = result[@"data"][@"userId"];
                            [self handleLoginSuccess];
                            [subscriber sendNext:self.userID];
                            [subscriber sendCompleted];
                        }];
                        return;
                    }
                    
                    // 2.绑定手机号逻辑
                    if (!isSuccessed) {
                        // 取号失败 或 手机未注册 sendError
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    
                    // 取号成功 才进行绑定号码
                    if (self.wechatCode.length > 0) {
                        [[self.wechatBindComand execute:nil] subscribeNext:^(id  _Nullable x) {
                            [subscriber sendNext:nil];
                            [subscriber sendCompleted];
                        } error:^(NSError * _Nullable error) {
                            [subscriber sendError:error];
                        }];
                    } else {
                        [[self.appleBindComand execute:nil] subscribeNext:^(id  _Nullable x) {
                            [subscriber sendNext:nil];
                            [subscriber sendCompleted];
                        } error:^(NSError * _Nullable error) {
                            [subscriber sendError:error];
                        }];
                    }
                }];
                
                return nil;
            }];
        }];
    }
    return _getTelByJPUSHTokenCommand;
}

/// 快速注册接口
- (RACCommand *)fastRegsiterCommand {
    if (!_fastRegsiterCommand) {
        @weakify(self);
        _fastRegsiterCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            
            RACTupleUnpack(NSString *communityID, NSString *tel, NSString *wechatOpenID, NSString *appleUserID) = input;
            NSString *encryptTel = [SEGEncryptRule encryptByRsaWithString:ValueToString(tel)];
            
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/fastRegister",nil];
                NSMutableDictionary *params = [@{@"tel": ValueToString(encryptTel),
                                         @"communityId" : ValueToString(communityID)} mutableCopy];
                if (wechatOpenID.length > 0) {
                    params[@"openId"] = wechatOpenID;
                }
                if (appleUserID.length > 0) {
                    params[@"iosUserId"] = appleUserID;
                }
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [self handleLoginSuccess];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _fastRegsiterCommand;
}


// 使用短信或密码登录
- (RACCommand *)loginCommand {
    if (!_loginCommand) {
        @weakify(self);
        _loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                RACTupleUnpack(NSString *tel, NSString *password, NSString *imgCode, NSString *randomToken, NSString *loginType) = input;
                
                [[SEGLoginV2Manager sharedManager] requestLoginByTel:tel password:password imgCode:imgCode randomToken:randomToken loginType:loginType finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        // 现在处于登录状态
                        [SEGLoginV2Manager seg_saveSignOutStatus:NO];
                        
                        [subscriber sendNext:@""];
                        [subscriber sendCompleted];
                    } else {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
                return nil;
            }];
        }];
    }
    return _loginCommand;
}

/// 使用短信验证码登录 或校验短信
- (RACCommand *)smsLoginOrCheckCommand {
    if (!_smsLoginOrCheckCommand) {
        @weakify(self);
        _smsLoginOrCheckCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v1/fast/login/validSms",nil];
                NSDictionary *params = @{@"tel": ValueToString(self.tel),
                                         @"smsCode" : ValueToString(self.smsCode),
                                         @"businessCode": @"register"};
               
                [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                        return;
                    }
                    self.userID = result[@"data"][@"userId"];
                    [self handleLoginSuccess];
                    [subscriber sendNext:self.userID];
                    [subscriber sendCompleted];
                }];
                
                return nil;
            }];
        }];
    }
    return _smsLoginOrCheckCommand;
}

- (void)handleLoginSuccess {
    // 登录成功 保存手机号
//    [SEGLoginV2Manager segSaveUserTelToLocal:self.tel];
}

@end
